<template>
    <div class="transfer-add-form">
        <div class="section">
            <h2 class="section-title">调拨基本信息</h2>
            <el-form ref="ruleFormRef" style="max-width: 1200px;margin: 20px;" :model="trf_order" status-icon
                :rules="rules" label-width="auto" class="demo-ruleForm">
                <el-form-item label="调拨单号" prop="trf_code">
                    <el-input v-model="trf_order.trf_code" placeholder="不输入则自动获取编号" />
                </el-form-item>

                <div class="form-columns">
                    <!-- 左侧表单 -->
                    <div class="form-column">
                        <el-form-item label="调拨类型" prop="trf_type" style="margin-bottom: 30px;">
                            <el-select v-model="trf_order.trf_type" placeholder="请选择调拨类型">
                                <el-option v-for="item in options" :key="item.dict_value" :label="item.dict_label"
                                    :value="item.dict_value" class="option-style" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="调出仓库" prop="warehouse_out_code" style="margin-bottom: 30px;">
                            <el-select v-model="trf_order.warehouse_out_code" placeholder="请选择调出仓库"
                                @change="handleOutWarehouseChange">
                                <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>
                    </div>

                    <!-- 右侧表单 -->
                    <div class="form-column">
                        <el-form-item label="调拨日期" prop="trf_startdate" style="margin-bottom: 30px;">
                            <el-date-picker v-model="trf_order.trf_startdate" type="datetime" placeholder="选择日期时间"
                                style="width: 100%;">

                            </el-date-picker>
                        </el-form-item>


                        <el-form-item label="调入仓库" prop="warehouse_enter_code" style="margin-bottom: 30px;">
                            <el-select v-model="trf_order.warehouse_enter_code" placeholder="请选择调入仓库"
                                @change="handleEnterWarehouseChange">
                                <el-option v-for="item in warehouses" :key="item.warehouse_code"
                                    :label="item.warehouse_name" :value="item.warehouse_code" />
                            </el-select>
                        </el-form-item>

                    </div>
                </div>
            </el-form>
        </div>

        <div class="section">
            <h2 class="section-title">调拨产品明细</h2>
            <div class="product-actions">
                <el-button type="primary" @click="productAdd">添加产品</el-button>
                <el-button @click="productDel">移除选中</el-button>
            </div>

            <el-table :data="selectedData" border style="width: 100%" :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" ref="selectedTable" @selection-change="handleSelectedChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="stock_name" label="货品名称" fixed="left" width="100" />
                <el-table-column prop="pro_code" label="货品编号" width="150" />
                <el-table-column prop="pro_brand" label="品牌" width="100" />
                <el-table-column prop="stock_model" label="规格型号" width="100" />
                <el-table-column label="单位" width="70">
                    <template #default="scope">
                        <span>{{ measureValue(scope.row.dict_code) }}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="stock_numder" label="当前库存" width="110" />
                <el-table-column label="调拨数量" width="100">
                    <template #default="scope">
                        <el-input v-model="scope.row.transfer_qty" style="width: 75px" :precision="2" :min="0"
                            :max="scope.row.stock_numder" />
                    </template>
                </el-table-column>

                <el-table-column prop="pro_cost_price" label="成本价" width="108" />
                <el-table-column prop="pro_sale_price" label="销售价" width="100" />
                <el-table-column label="成本合计" width="120">
                    <template #default="scope">
                        <span>{{ (scope.row.transfer_qty * scope.row.pro_cost_price).toFixed(2) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="金额合计" width="110">
                    <template #default="scope">
                        <span>{{ (scope.row.transfer_qty * scope.row.pro_sale_price).toFixed(2) }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <div class="summary-row">
                <span>合计</span>
                <div class="summary-values">
                    <span>调拨总数量：{{ transfer_total_qty }}</span>
                    <span>成本总额：{{ cost_total_price.toFixed(2) }}</span>
                    <span>金额总额：{{ amount_total_price.toFixed(2) }}</span>
                </div>
            </div>
        </div>

        <div class="button-group">
            <el-button type="primary" @click="handleAdd">保存</el-button>
            <el-button @click="handleClose">关闭</el-button>
        </div>
    </div>

    <!-- 添加产品模态框 -->
    <el-dialog v-model="dialogTableVisible" width="800" title="添加产品">
        <hr>
        <div class="product-filter">
            <el-input v-model="productcode" placeholder="请输入货品编号" style="width: 240px; margin-right: 20px;" />
            <el-select v-model="dict_code" placeholder="请选择单位" style="width: 240px">
                <el-option v-for="item in measureOptios" :key="item.dict_value" :label="item.dict_label"
                    :value="item.dict_value" />
            </el-select>
            <el-button @click="productReset">重置</el-button>
            <el-button type="primary" @click="productSearch">查询</el-button>
        </div>
        <transition name="fade" mode="out-in">
            <div :key="currentPage"> <!-- 添加这个包裹元素 -->
                <el-table ref="multipleTableRef" :data="productData" :cell-style="{ textAlign: 'center' }"
                    :header-cell-style="{
                textAlign: 'center',
                background: '#f5f7fa',
                fontWeight: 'bold',
                position: 'sticky',
                top: 0
            }" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" :selectable="isProductSelectable" />
                    <el-table-column property="pro_code" label="货品编号" width="180" />
                    <el-table-column property="stock_name" label="货品名称" width="200" />
                    <el-table-column property="stock_model" label="规格型号" />
                    <el-table-column label="单位">
                        <template #default="scope">
                            <span>{{ measureValue(scope.row.dict_code) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column property="pro_cost_price" label="成本价" />
                    <el-table-column property="pro_sale_price" label="销售价" />
                    <el-table-column property="stock_numder" label="当前库存" />
                </el-table>

                <div class="pagination">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[5, 10, 20, 50]" :small="false" :background="true"
                        layout="total, sizes, prev, pager, next, jumper" :total="pageCount"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                </div>
            </div> <!-- 结束包裹元素 -->
        </transition>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import { useRouter } from 'vue-router';
import { ElMessage} from 'element-plus';

const router = useRouter();

// 调拨类型
const options = ref([])
// 仓库列表
const warehouses = ref([]);




// 调拨单对象
let trfAdd = {
    trf_type: "", // 调拨类型
    trf_code: "", // 调拨单号
    trf_applicant: localStorage.getItem('userLName'), // 申请人
    trf_startdate: "", // 调拨日期
    
    warehouse_out_code: "",
    warehouse_out_name: "",
    warehouse_enter_code: "",
    warehouse_enter_name: "",
   
    trf_audit_by: "", // 审核人
   
    trf_audit_status: "", // 审核状态
    trf_audit_opinion: "", // 审核备注
    
    del_flag: '0', // 删除状态
    create_by: localStorage.getItem('userLName'), // 创建人
    create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'), // 创建时间 

    trf_ckpd:'0',
    trf_rkpd:'0',
    
}

// 调拨单表单对象
const trf_order = reactive({ ...trfAdd })

// 表单验证
const ruleFormRef = ref(null)
const rules = reactive({
    warehouse_out_code: [{ required: true, message: '请选择调出仓库', trigger: 'change' }],
    warehouse_enter_code: [{ required: true, message: '请选择调入仓库', trigger: 'change' }],
    trf_type: [{ required: true, message: '请选择调拨类型', trigger: 'change' }],
    trf_startdate: [{ required: true, message: '请选择调拨日期', trigger: 'change' }]
});

// 产品相关状态
// 产品相关状态
const dialogTableVisible = ref(false) // 控制添加产品模态框的显示/隐藏
const productData = ref([])          // 存储从API获取的产品列表数据
const currentPage = ref(1)           // 产品列表的当前页码
const pageSize = ref(5)              // 每页显示的产品数量
const pageCount = ref(0)             // 产品列表的总记录数（用于分页）

const productcode = ref("")          // 产品搜索关键字（名称/编号）
const dict_code = ref("0")           // 选中的计量单位ID（用于筛选）

const measureOptios = ref([])        // 存储计量单位选项列表
const multipleTableRef = ref(null);  // 产品选择表格的DOM引用
const selectedProducts = ref([]);    // 在产品模态框中临时选中的产品
const selectedTable = ref(null);     // 已选产品表格的DOM引用
const selectedRows = ref([]);        // 在已选产品表格中选中的行
const selectedData = ref([]);        // 最终确认添加到调拨单中的产品列表

// 调拨单统计信息
const transfer_total_qty = ref(0)    // 调拨单中所有产品的调拨数量总和
const cost_total_price = ref(0)      // 调拨单中所有产品的成本总价（成本价×数量）之和
const amount_total_price = ref(0)    // 调拨单中所有产品的金额总和（销售价×数量）之和



// 监听产品明细变化
watch(selectedData, (newVal) => {
    transfer_total_qty.value = 0
    cost_total_price.value = 0
    amount_total_price.value = 0

    newVal.forEach(row => {
        if (isNaN(Number(row.transfer_qty))) {
            ElMessage.warning('调拨数量必须是数字');
            row.transfer_qty = 0;
        }

        if (row.transfer_qty > row.stock_numder) {
            ElMessage.warning(`调拨数量不能大于当前库存`);
            row.transfer_qty = row.stock_numder
        }

        // 计算总成本
        const cost = (row.transfer_qty || 0) * (row.pro_cost_price || 0);
        // 计算总金额
        const amount = (row.transfer_qty || 0) * (row.pro_sale_price || 0);

        transfer_total_qty.value += Number(row.transfer_qty)
        cost_total_price.value += cost
        amount_total_price.value += amount
    });
}, { deep: true });





// 调出仓库变化
const handleOutWarehouseChange = (selectedValue) => {
    const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
    trf_order.warehouse_out_name = selectedItem?.warehouse_name || "";


};

// 调入库区变化
const handleEnterWarehouseChange = (selectedValue) => {
    if(trf_order.warehouse_enter_code===trf_order.warehouse_out_code){
        ElMessage.warning('调入仓库不能与调出仓库相同,请重新选择');
        trf_order.warehouse_enter_code="";
        trf_order.warehouse_enter_name="";
    }else{
        const selectedItem = warehouses.value.find(item => item.warehouse_code === selectedValue);
        trf_order.warehouse_enter_name = selectedItem?.warehouse_name || "";
    }
};


// 添加产品    
const productAdd = () => {
    if (!trf_order.warehouse_out_code) {
        ElMessage.warning('请先选择调出仓库');
        return;
    }
    dialogTableVisible.value = true;
    productFill();
    productCount();
};

// 移除选中的产品
const productDel = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请先选择要移除的数据');
        return;
    }

    // 创建一个包含选中项的 stock_entry_no 和 pro_code 的数组
    const selectedEntries = selectedRows.value.map(item => ({
        stock_entry_no: item.stock_entry_no,
        pro_code: item.pro_code
    }));

    // 过滤掉被选中的项
    selectedData.value = selectedData.value.filter(item => {
        // 检查当前项的 stock_entry_no 和 pro_code 是否不在选中的数组中
        return !selectedEntries.some(
            selected =>
                selected.stock_entry_no === item.stock_entry_no &&
                selected.pro_code === item.pro_code
        );
    });

    if (selectedTable.value) {
        selectedTable.value.clearSelection();
    }
    selectedRows.value = [];
};

// 分页查询产品库存信息
const productFill = () => {
   
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select_stock_All", {
        params: {
            weahouse_code: trf_order.warehouse_out_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        productData.value = result.data || []
        console.info(productData.value)
    }).catch((err) => {
        console.error(err); 
        ElMessage.error('获取产品数据失败');
    });
};

// 查询产品库存总数
const productCount = () => {
    axios.get("http://localhost:5181/api/Inv_Stock/Get_Select__stock_Count", {
        params: {
            weahouse_code: trf_order.warehouse_out_code,
            pro_code: productcode.value,
            dict_code: dict_code.value,
        },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        pageCount.value = result.data || 0
    }).catch((err) => {
        console.error(err);
    });
};

// 分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    productFill();
};

// 当前页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    productFill();
};

// 查询计量单位
const getMeasure = () => {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: { dict_type: "db_measure" },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        measureOptios.value = [{ dict_value: "0", dict_label: "请选择单位" }, ...(result.data || [])];
    }).catch((err) => {
        console.error(err);
    });
};

// 根据计量单位id返回计量单位名称
const measureValue = (row) => {
    if (!row) return "无";
    const unit = measureOptios.value.find((item) => item.dict_value == row);
    return unit ? unit.dict_label : "无";
};

// 查询产品
const productSearch = () => {
    productFill();
    productCount();
};

// 重置产品查询条件
const productReset = () => {
    productcode.value = "";
    dict_code.value = "0";
    productFill();
    productCount();
};

// 表格选择变化时的处理函数
const handleSelectionChange = (val) => {
    selectedProducts.value = val;
};

// 点击确定存储选择的产品数据
const handleConfirmSelection = () => {
    selectedData.value = [
        ...selectedData.value,
        ...selectedProducts.value.map(item => ({
            ...item,
            transfer_qty: 0,
            pro_total_cost: 0,
            pro_total_amount: 0

        }))
    ];

    dialogTableVisible.value = false;
    if (multipleTableRef.value) {
        multipleTableRef.value.clearSelection();
    }
};

// 表格选择变化时处理数据
const handleSelectedChange = (val) => {
    selectedRows.value = val;
};

// 判断产品是否可选（防止重复添加）
const isProductSelectable = (row) => {
    return !selectedData.value.some(
        item => item.pro_code === row.pro_code && item.stock_entry_no === row.stock_entry_no
    );
};

// 保存调拨单
const handleAdd = async () => {
    try {

     const valid = await ruleFormRef.value.validate().catch(() => false);
        if (!valid) {
            ElMessage.warning('请先完善必填项');
            return;
        }


        // 验证表单
        if (!trf_order.warehouse_out_code || !trf_order.warehouse_enter_code) {
            ElMessage.warning('请选择调出仓库和调入仓库');
            return;
        }

        if (selectedData.value.length === 0) {
            ElMessage.warning('请添加调拨产品');
            return;
        }

        // 生成调拨单号
        await obtainCode();



        // 保存主表信息
        const mainResponse = await axios.put(
            "http://localhost:5181/api/Inv_trf/Inv_trf_Insert",
            trf_order,
            { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (mainResponse.data > 0) {
           
            // 获取主表ID
         
            const trfId = await Select_inv_id();
           
            
            // 转换明细数据
            const detailList = selectedData.value.map(item => ({
                trf_id: trfId,
                pro_name: item.stock_name,
                pro_code: item.pro_code,
                pro_brand: item.pro_brand,
                pro_model: item.stock_model,
                unitmeas_id: String(item.dict_code),
                inventory_numder: item.transfer_qty,
                pro_cost_price: item.pro_cost_price,
                pro_sale_price: item.pro_sale_price,
                stock_entry_no: item.stock_entry_no,
                Pending_numder: item.transfer_qty
            }));
          console.log(detailList);
            
            // 保存明细
            await saveTransferDetails(detailList);

            ElMessage.success('调拨单创建成功');

            // 清空表单
            Object.assign(trf_order, trfAdd);
            selectedData.value = [];

            //跳回
            router.push('/main/Inv/InvTrf');
        } else {
            ElMessage.error("主表保存失败");
        }
    } catch (error) {
        console.error("保存出错:", error);
        ElMessage.error("保存过程中发生错误");
    }
};
//根据新添加的Id来获取信息
const Select_inv_id = async () => {
    const response = await axios.get(
        "http://localhost:5181/api/Inv_trf/inv_tfr_id",
        {
            params: { trf_code: trf_order.trf_code },
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        }
    );
    return response.data; // 直接返回ID值
};


// 保存调拨明细
const saveTransferDetails = (detailList) => {
    return axios.put(
        "http://localhost:5181/api/Inv_trf/Inv_trf_Inserttrfproddtl",
        detailList,
        { headers: { authorization: `Bearer ${localStorage.getItem('token')}` } }
    );
};

// 获取调拨单号
const obtainCode = async () => {
    try {
        const result = await axios.get("http://localhost:5181/api/DJBH/DJBH", {
            params: { en_code: 14 }, // 假设调拨单编号规则为10
            headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        trf_order.trf_code = result.data;
    } catch (err) {
        console.error("生成单号失败:", err);
        throw err;
    }
};

// 关闭页面
const handleClose = () => {
    router.push('/main/Inv/InvTrf');
};

// 查询调拨类型
const getTransferTypes = () => {
    axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: { dict_type: "inv_trf" },
        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then((result) => {
        options.value = result.data || [];
    }).catch((err) => {
        console.error(err);
    });
};

// 查询仓库信息
const getWarehouses = () => {
    axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: { 'Authorization': 'Bearer ' + localStorage.getItem('token') }
    }).then((res) => {
        warehouses.value = res.data || [];
    }).catch((res) => {
        console.log(res);
    });
};

onMounted(() => {
    getTransferTypes();
    getMeasure();
    getWarehouses();
   
});
</script>

<style scoped>
.transfer-add-form {
    padding: 20px;
    background-color: #fff;
    position: relative;
    min-height: 100vh;
}

.section {
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #333;
    border-bottom: 1px solid #eee;
    padding-bottom: 10px;
}

.form-columns {
    display: flex;
    justify-content: space-between;
    gap: 20px;
}

.form-column {
    flex: 1;
}

.product-actions {
    margin-bottom: 15px;
    display: flex;
}

.summary-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
  
    border-top: none;
    margin-top: -1px;
}

.summary-values {
    display: flex;
    gap: 20px;
    font-weight: bold;
}

.summary-values span {
    padding: 2px 10px;
    border-radius: 4px;
}

.button-group {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;
}

.product-filter {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
}

.pagination {
    display: flex;
    justify-content: center;
    margin: 15px 0;
}

.order-filter {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    gap: 10px;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}

.order-input :deep(.el-input__inner) {
    cursor: pointer;
    background-color: #f5f7fa;
}

.order-input:hover :deep(.el-input__inner) {
    border-color: #c0c4cc;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    padding-top: 15px;
    border-top: 1px solid #ebeef5;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f5f7fa !important;
    cursor: pointer;
}
</style>